package com.ftp.longdistance.util;

import com.ftp.longdistance.bean.Ftp;
import com.ftp.longdistance.exception.BizException;
import com.ftp.longdistance.ftpmapper.service.PointOfJunction;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/**
 * @author TanYongPeng
 * <p>
 *     loing 工具类
 * </p>
 */
@Slf4j
public class LoginUtils {

    /**
     * 登录成功后添加相关信息
     * @param ftp
     * @param request
     * @param state
     * @return
     */
    public static boolean recordLogin(Ftp ftp, HttpServletRequest request, boolean state){
        if (request.getSession().getAttribute("userName") != null){
            throw new BizException("108","session未过期 无需重复登录");
        }
        ftp.setPort(ftp.getPort() == null?21:ftp.getPort());
        ftp.setTimedOut(ftp.getTimedOut() == null?5000:ftp.getTimedOut());
        log.info("ftp = {}",ftp);
        if (state){
            request.getSession().setAttribute("currentDirectory","/");
            request.getSession().setAttribute("ftpType",ftp.getFtpType());
            request.getSession().setAttribute("userName",ftp.getUserName());
            request.getSession().setAttribute("host",ftp.getFtpHost());
            return true;
        }else {
            throw new BizException("106","连接异常");
        }
    }

    /**
     * 登录验证
     * @param ftp
     * @param request
     * @param p
     * @return
     */
    public static boolean login(Ftp ftp, HttpServletRequest request, PointOfJunction p) {
        boolean connect = p.getConnect(ftp);
        return recordLogin(ftp,request,connect);
    }

    /**
     * 退出登录
     * @param request
     * @param p
     */
    public static void loginOut(HttpServletRequest request,PointOfJunction p) {
        request.getSession().invalidate();
        p.logout();
    }
}
